//
//  SJSettingViewController.m
//  WSL
//
//  Created by CJ on 2017/12/8.
//  Copyright © 2017年 sanjuetech. All rights reserved.
//

#import "SJSettingViewController.h"
#import "SJSettingCell.h"
#import "SJUserInfoItem.h"
#import "SJSetNameViewController.h"
#import "SJsetIntroViewController.h"
#import "SJBindPhoneViewController.h"
#import "SJSetPasswordViewController.h"
#import "SJSetGenderViewController.h"
#import "SJWebViewController.h"

@interface SJSettingViewController () <UITableViewDelegate, UITableViewDataSource>


@property (nonatomic ,strong) UITableView *tableView;
@property (nonatomic ,strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UIView *navigationBarView;
@property (nonatomic, strong) SJUserInfoItem *myInfo;

@end

@implementation SJSettingViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [SJStatisticTool beginLogPageView:NSStringFromClass([self class])];
    
    [self configData];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [SJStatisticTool endLogPageView:NSStringFromClass([self class])];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view
    
    [self setupUI];
}


- (void)configData {
    
    
    SJUserInfoItem *myInfo = [SJUserInfoItem modelWithJSON:[SJUserDefaults objectForKey:SJUserInfo]];
    
    self.myInfo = myInfo;
    
    [self.dataArray removeAllObjects];
    
    NSDictionary *section0row0 = @{
                                   @"title": @"昵称",
                                   @"detail": myInfo.name?myInfo.name:@""
                                   };
    
    NSDictionary *section0row1 = @{
                                   @"title": @"性别",
                                   @"detail": myInfo.gender?myInfo.gender:@""
                                   };
    
    NSDictionary *section0row2 = @{
                                   @"title": @"自我介绍",
                                   @"detail": myInfo.intro?myInfo.intro:@""
                                   };
    
    [self.dataArray addObject:@[section0row0, section0row1, section0row2]];
    
    
    NSDictionary *section1row0 = @{
                                   @"title": @"设置密码",
                                   @"detail": @""
                                   };
    
    NSDictionary *section1row1 = @{
                                   @"title": @"手机号",
                                   @"detail": myInfo.phone?myInfo.phone:@""
                                   };
    
    [self.dataArray addObject:@[section1row0, section1row1]];
    
    
    NSDictionary *section2row0 = @{
                                   @"title": @"清除缓存",
                                   @"detail": @""
                                   };
    
//    NSDictionary *section2row1 = @{
//                                   @"title": @"显示标题",
//                                   @"detail": @""
//                                   };
    
    [self.dataArray addObject:@[section2row0]];
    
    
    NSDictionary *section3row0 = @{
                                   @"title": @"客服中心",
                                   @"detail": @""
                                   };
    
    NSDictionary *section3row1 = @{
                                   @"title": @"关于思藏",
                                   @"detail": @""
                                   };
    
    [self.dataArray addObject:@[section3row0, section3row1]];
    
    
    NSDictionary *section4row0 = @{
                                   @"title": @"退出登录",
                                   @"detail": @""
                                   };
    
    [self.dataArray addObject:@[section4row0]];

    
    [self.tableView reloadData];
    
}


- (void)setupUI {
    
    [self.view addSubview:self.tableView];
    self.tableView.sd_layout.spaceToSuperView(UIEdgeInsetsZero);
    
    [self.view addSubview:self.navigationBarView];
    
    if (812 == SJScreenH) {
        self.navigationBarView.sd_layout
        .leftSpaceToView(self.view, SJLayoutFrame(0))
        .topSpaceToView(self.view, SJLayoutFrame(40))
        .heightIs(SJLayoutFrame(50))
        .widthIs(SJScreenW);
    } else {
        self.navigationBarView.sd_layout
        .leftSpaceToView(self.view, SJLayoutFrame(0))
        .topSpaceToView(self.view, SJLayoutFrame(0))
        .heightIs(SJLayoutFrame(50))
        .widthIs(SJScreenW);
    }
    
}

#pragma mark - getter

- (UIView *)navigationBarView{
    
    if (!_navigationBarView) {
        
        _navigationBarView = [UIView new];
        _navigationBarView.backgroundColor = [UIColor clearColor];
        
        // 返回
        UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [backButton setImage:[UIImage imageNamed:@"addtext-icon-return"] forState:UIControlStateNormal];
        [backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
        
        [_navigationBarView addSubview:backButton];
        backButton.sd_layout
        .centerYEqualToView(_navigationBarView)
        .leftSpaceToView(_navigationBarView, SJLayoutFrame(10))
        .heightIs(SJLayoutFrame(30))
        .widthIs(SJLayoutFrame(30));
        
        UILabel *wordLabel = [UILabel new];
        wordLabel.textColor = SJColorHexString(@"#ffffff");
        wordLabel.font = [UIFont fontWithName:@"Helvetica" size:SJLayoutFrame(17)];
        wordLabel.textAlignment = NSTextAlignmentCenter;
        
        wordLabel.text = @"设置";
        [_navigationBarView addSubview:wordLabel];
        wordLabel.sd_layout
        .centerYEqualToView(_navigationBarView)
        .centerXEqualToView(_navigationBarView)
        .heightIs(SJLayoutFrame(27));
        [wordLabel setSingleLineAutoResizeWithMaxWidth:SJScreenW * .5];
        
    }
    return _navigationBarView;
}

- (void)backAction {
    
    [self.navigationController popViewControllerAnimated:YES];
}


- (NSMutableArray *)dataArray {
    
    if (!_dataArray) {
        
        _dataArray = [[NSMutableArray alloc] init];  // 分四个 Section
        
        
    }
    return _dataArray;
}

- (UITableView *)tableView {
    
    if (!_tableView) {
        
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
        _tableView.separatorColor = [UIColor clearColor];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.bounces = NO;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.contentInset = UIEdgeInsetsMake(SJLayoutFrame(50), 0, 0, 0);
        
        [_tableView registerClass:[SJSettingCell class] forCellReuseIdentifier:NSStringFromClass([SJSettingCell class])];
        
        
    }
    return _tableView;
}

#pragma mark - Action

- (void)exitAction {
    
    
    UIColor *bgColor = SJColorHexString(@"#00000090");
    
    WeakSelf;
    [LEEAlert alert].config
    .LeeAddTitle(^(UILabel *label) {
        
        label.text = @"退出确认";
        label.textColor = [UIColor whiteColor];
    })
    .LeeAddContent(^(UILabel *label) {
        
        label.text = @"确定退出当前账号？";
        label.textColor = [UIColor whiteColor];
    })
    .LeeAddAction(^(LEEAction *action) {
        
        action.type = LEEActionTypeCancel;
        action.title = @"取消";
        action.titleColor = [UIColor whiteColor];
        action.backgroundColor = bgColor;
        action.clickBlock = ^{
            
            // 取消点击事件Block
        };
    })
    .LeeAddAction(^(LEEAction *action) {
        
        action.type = LEEActionTypeDefault;
        action.title = @"确定";
        action.titleColor = [UIColor whiteColor];
        action.backgroundColor = bgColor;
        action.clickBlock = ^{
            
            YYImageCache *cache = [YYWebImageManager sharedManager].cache;
            [cache.memoryCache removeAllObjects];
            [cache.diskCache removeAllObjects];
            
            [SJUserDefaults setObject:nil forKey:SJToken];
            [SJUserDefaults setObject:nil forKey:SJUserInfo];
            [SJUserDefaults synchronize];
            
            [weakSelf.navigationController popToRootViewControllerAnimated:YES];
        };
    })
    .LeeHeaderColor(bgColor)
    .LeeBackgroundStyleTranslucent(0)
    .LeeCornerRadius(SJLayoutFrame(5))
    .LeeClickBackgroundClose(YES)
    .LeeShow();
    
    
    
}


- (void)setName {
    
    SJSetNameViewController *setVC = [SJSetNameViewController new];
    setVC.myInfo = self.myInfo;
    [self.navigationController pushViewController:setVC animated:YES];
    
}

- (void)setGender {
    
    SJSetGenderViewController *setVC = [SJSetGenderViewController new];
    setVC.myInfo = self.myInfo;
    [self.navigationController pushViewController:setVC animated:YES];
    
}

- (void)setIntro {
    
    SJsetIntroViewController *setVC = [SJsetIntroViewController new];
    setVC.myInfo = self.myInfo;
    [self.navigationController pushViewController:setVC animated:YES];
    
}

- (void)bindPhone {
    
    SJBindPhoneViewController *setVC = [SJBindPhoneViewController new];
    [self.navigationController pushViewController:setVC animated:YES];
    
}

- (void)setPassword {
    
    SJSetPasswordViewController *setVC = [SJSetPasswordViewController new];
    setVC.phoneStr = self.myInfo.phone;
    [self.navigationController pushViewController:setVC animated:YES];
    
}

- (void)webView:(NSString *)url title:(NSString *)title {
    
    SJWebViewController *webVC = [SJWebViewController new];
    webVC.url = [NSURL URLWithString:url];
    webVC.title = title;
    [self.navigationController pushViewController:webVC animated:YES];
    
}


- (void)removeCache {
    
    YYImageCache *cache = [YYWebImageManager sharedManager].cache;
    
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeGradient];
    [SVProgressHUD showWithStatus:@"正在清除..."];
    // 清空缓存
    [cache.memoryCache removeAllObjects];
    
    // 清空磁盘缓存，带进度回调
    
    [cache.diskCache removeAllObjectsWithProgressBlock:^(int removedCount, int totalCount) {
        // progress
    } endBlock:^(BOOL error) {
        
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];
        [SVProgressHUD showSuccessWithStatus:@"清除完成"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
    }];
}

#pragma mark - tableview delegate and datasource

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSDictionary *item = self.dataArray[indexPath.section][indexPath.row];
    
    if ([item[@"title"] isEqualToString:@"退出登录"]) {
        [self exitAction];
        
        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
        attributes[@"name"] = item[@"title"];
        [SJStatisticTool event:@"logout" attributes:attributes];
    }
    
    if ([item[@"title"] isEqualToString:@"清除缓存"]) {
        [self removeCache];
        
        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
        attributes[@"name"] = item[@"title"];
        [SJStatisticTool event:@"removeCache" attributes:attributes];
    }
    
    if ([item[@"title"] isEqualToString:@"昵称"]) {
        [self setName];
    }
    
    if ([item[@"title"] isEqualToString:@"性别"]) {
        [self setGender];
    }
    
    if ([item[@"title"] isEqualToString:@"自我介绍"]) {
        [self setIntro];
    }
    
    if ([item[@"title"] isEqualToString:@"手机号"]) {
        
        if ([item[@"detail"] isEqualToString:@""]) {
            
            [self bindPhone];
        }
    }
    
    if ([item[@"title"] isEqualToString:@"设置密码"]) {
        
        if (![_myInfo.phone isEqualToString:@""]) {
            [self setPassword];
        } else {
            [SVProgressHUD showInfoWithStatus:@"请绑定手机"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
        }
    }
    
    if ([item[@"title"] isEqualToString:@"客服中心"]) {
        [self webView:@"http://i.sanjuetech.com/engine/get_server" title:item[@"title"]];
    }
    
    if ([item[@"title"] isEqualToString:@"关于思藏"]) {
        [self webView:@"http://i.sanjuetech.com/engine/get_about" title:item[@"title"]];
    }
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.dataArray[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    SJSettingCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SJSettingCell class])];
    
    NSDictionary *item = self.dataArray[indexPath.section][indexPath.row];
    
    cell.item = item;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return SJItemWH + SJMargin;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return SJLayoutFrame(21);
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    return [UIView new];
}

@end
